import React from 'react';
import {
    View,
    ScrollView,
    Text,
    TextInput,
    TouchableHighlight,
    Image,
    InteractionManager,
    ActionSheetIOS
} from 'react-native';

import commonStyles from '../../styles/commonstyles';
import DatePicker from 'react-native-datepicker';
import NetUtil from '../../common/NetUtil';
import config from '../../config/config';
import moment from 'moment';
import { toast,showLoading,hideLoading } from '../../utils/NativeUtil';
import {connect} from 'react-redux';

import { NavigationActions } from 'react-navigation'
import LmmKeyboardAvoidingView from '../../component/LmmKeyboardAvoidingView'
import { getTickets } from './actions';

class TicketAddItem extends React.Component {

    constructor(props) {
        super(props);

        this.eventLst=[];
    
        if (props.ticket == undefined) {
            this.ticket = '';
            this.ticketid = '';
            this.lat = "";
            this.lng = "";
            this.state = {
              yxq_start:'',
              yxq_end:'',
              tfq_start:'',
              tfq_end:'',
              curdateview:'',//记录当前所选控件
              tempDate:new Date(),
              date:new Date(),
              ticketname: '',
              ticketnum: '',
              ticketmoney: '',
              consumeMoney: '',
              moneyNote: '', //使用范围
              ischoose: "未选",
              eventstr:'摇一摇',
              'event':'YYY',
            }
        }else{
            this.initData(props);
        }
      }
    
    
      initData(props){
        this.ticket = props.ticket;
        this.ticketid = this.ticket.ticketId;
        this.lat = this.ticket.lat;
        this.lng = this.ticket.lng;
        if (this.ticket.event == "YYY") {
          this.eventprops = '摇一摇';
        }else if (this.ticket.event == "AR") {
          this.eventprops = 'AR红包';
        }else if (this.ticket.event == "USERBUY") {
          this.eventprops = '购物返券';
        }
    
        let temptfq_s = '';
        if(this.ticket.receiveStart != undefined){
            temptfq_s = moment.unix(this.ticket.receiveStart / 1000).format("YYYY-MM-DD HH:mm:ss");
        } else {
            temptfq_s =  '';
        }
    
        let temptfq_e = '';
        if (this.ticket.receiveEnd != undefined) {
            temptfq_e = moment.unix(this.ticket.receiveEnd / 1000).format("YYYY-MM-DD HH:mm:ss");
        }else {
            temptfq_e =  '';
        }
    
    let tempyxq_s = '';
        if (this.ticket.start != undefined) {
            tempyxq_s = moment.unix(this.ticket.start / 1000).format("YYYY-MM-DD HH:mm:ss");
        }else{
            tempyxq_s =  '';
        }
    
    let tempyxq_e = '';
        if (this.ticket.end != undefined) {
            tempyxq_e = moment.unix(this.ticket.end / 1000).format("YYYY-MM-DD HH:mm:ss");
        }else {
            tempyxq_e =   '' ;
        }
    
        this.state = {
          curdateview:'',//记录当前所选控件
          tempDate:new Date(),
          date:new Date(),
          yxq_start:tempyxq_s,
          yxq_end:tempyxq_e,
          tfq_start:temptfq_s,
          tfq_end:temptfq_e,
          ticketname: this.ticket.name,
          ticketnum: this.ticket.num + '',
          ticketmoney: this.ticket.money + '',
          consumeMoney: this.ticket.consumeMoney + '',
          moneyNote: this.ticket.moneyNote, //适用范围
          ischoose: "已选",
          eventstr:this.eventprops,
          'event':this.ticket.event,
        }
      }
    
    
    //   componentDidMount() {
    //     InteractionManager.runAfterInteractions(() => {
    //       this.getEvent();
    //     });
    //   }
    
    //   getEvent(){
    //     var self = this;
    //     let url = '/s/ticket/getStrategyList';
    //     const params = {
    //         token: this.props.token,
    //     }
    //     NetUtil.postSign(config.apiUrl + url , params , function(res){
    //         console.log(res);
    //         if (res.success) {
    //           self.eventLst = res.data.list;
    //         }else{
    //           uiPlugin.toast("获取类别失败");
    //           self._backToFront();
    //         }
    //     });
    //   }

    toastmessage(message) {
        toast(message);
      }
    
      _backToFront() {
        this.props.navigation.dispatch(NavigationActions.back());
      }
    
      BASEisInt = (obj) => {
          //判断是否为整数
          var re = /[1-9]\d*/;
          return re.test(obj);
      }
    
      //保存
      saveticket() {
        var self = this;
        if (this.state.ticketname == "") {
          this.toastmessage("请填写券名称");
          return;
        }
    
        if (this.state.ticketnum == "") {
            this.toastmessage("请填写券的数量");
          return;
        }
          // console.log(this.BASEisInt(this.state.ticketnum));
          // if (!this.BASEisInt(this.state.ticketnum)) {
          //   uiPlugin.toast("请填写正确券数量");
          //   return;
          // }
    
    
        if (this.state.ticketmoney == ""){
            this.toastmessage("请填写券的价格");
          return;
        }
    
    
        let consumeMoney = this.state.consumeMoney;
        if (parseFloat(consumeMoney) != consumeMoney){
            this.toastmessage("消费满多少金额可使用请填写数字");
               return;
        }
    
        // if (this.lat == ""){
        //   self.toastmessage("请选择投放地址");
        //   return;
        // }
    
        const params = {
          token: this.props.token,
          name: this.state.ticketname,
          money: this.state.ticketmoney*100,
          num: this.state.ticketnum,
          consumeMoney: this.state.consumeMoney*100,
          rangeValue: this.shopid,
          start:this.state.yxq_start,
          end:this.state.yxq_end,
          moneyNote:this.state.moneyNote,
          lat:this.lat,
          lng:this.lng,
          receiveStart:this.state.tfq_start,
          receiveEnd:this.state.tfq_end,
        //   event:this.state.event,
          event: ''
        };
    
        let url  = '';
        if (this.ticketid == '') {
          url = '/s/ticket/addShopCoupon';
          this.showLoading("正在添加");
        } else {
          url = '/s/ticket/editShopCoupon';
          params.ticketId = this.ticketid;
          this.showLoading("正在更新");
        }
    
        NetUtil.postSign(config.apiUrl + url , params,function(res){
            self.hideLoading()
            if (res.success) {
                self._backToFront();
                self.props.getTickets(self.props.token,1);
                self.toastmessage("成功");
            } else {
                self.toastmessage(res.message);
            }
        });
      }

      showLoading(message) {
        showLoading(message);
      }

      hideLoading() {
        hideLoading();
      }
    
      //设置位置
    //   setlocation() {
    //     const self = this;
    //     commonPlugin.getLatLng((lat, lng) => {
    //       self.lat = lat;
    //       self.lng = lng;
    //       console.log(self.lat);
    //       if (self.lat != ""){
    //          self.setState({
    //            "ischoose": "已选"
    //          })
    //       }else{
    //           self.setState({
    //            "ischoose": "未选"
    //          })
    //       }
    //     });
    //   }
    
    //   showActionSheet() {
    //     var BUTTONS = [];
    //     for (var i = 0; i < this.eventLst.length; i++) {
    //         BUTTONS[i] = this.eventLst[i].name;
    //     }
    //     let CANCEL_INDEX = this.eventLst.length;
    //     BUTTONS[this.eventLst.length] = '取消';
    //     ActionSheetIOS.showActionSheetWithOptions({
    //       options: BUTTONS,
    //       cancelButtonIndex: CANCEL_INDEX,
    //       destructiveButtonIndex: -1,
    //     },
    //     (buttonIndex) => {
    //         if (buttonIndex < this.eventLst.length ) {
    //         let temp = this.eventLst[buttonIndex].value;
    //         this.setState({
    //           'event':temp,
    //           eventstr:BUTTONS[buttonIndex],
    //       });
    //     }
    //   });
    // }

    render() {
      let saveBtn = undefined;
      if (this.ticket == '') {
        saveBtn = <TouchableHighlight
          onPress={()=>this.saveticket()}
          underlayColor='rgba(255,255,255,0)'>
          <View style={[commonStyles.greenbtn , {marginTop:15 ,marginBottom:15}]}>
            <Text style={commonStyles.greenbtn_txt}>保存</Text>
          </View>
        </TouchableHighlight>
      }
        return (<LmmKeyboardAvoidingView keyboardVerticalOffset={ 64 }>
            <ScrollView>
            <View style={commonStyles.itembar}>
              <Text>优惠券名称</Text>
              <TextInput
              style={{flex:1 ,alignItems:'flex-end' ,justifyContent:'flex-end',paddingLeft:10 ,width:40}}
              placeholder="请输入名称"
              underlineColorAndroid={'transparent'}
              value={this.state.ticketname}
              textAlign='right'
              writingDirection='rtl'
              onChangeText={(text)=>this.setState({
                ticketname:text,
              })}
              returnKeyType='next'
              multiline={false}
              />
            </View>
            <View style={commonStyles.line_gray}/>
            <View style={commonStyles.itembar}>
                <Text>券数量</Text>
                <TextInput
                  placeholder="请输入要发布的券数量"
                  underlineColorAndroid={'transparent'}
                  style={{flex:1 ,alignItems:'flex-end' ,justifyContent:'flex-end',paddingLeft:10 ,width:40}}
                  textAlign='right'
                  writingDirection='rtl'
                  keyboardType='numeric'
                  value={this.state.ticketnum}
                  onChangeText={(text)=>this.setState({
                    ticketnum:text,
                  })}
                  returnKeyType='next'
                  multiline={false}
                />
            </View>
            <View style={commonStyles.line_gray}/>
            <View style={commonStyles.itembar}>
                <Text>券价格</Text>
                <TextInput
                  style={{flex:1 ,alignItems:'flex-end' ,justifyContent:'flex-end',paddingLeft:10 ,width:40}}
                  placeholder="(元)"
                  underlineColorAndroid={'transparent'}
                  textAlign='right'
                  keyboardType='numeric'
                  value={this.state.ticketmoney}
                  writingDirection='rtl'
                  onChangeText={(text)=>this.setState({
                    ticketmoney:text,
                  })}
                  returnKeyType='next'
                  multiline={false}
                />
            </View>
            <View style={commonStyles.line_gray}/>
            <View style={commonStyles.itembar}>
                <Text>满减金额</Text>
                <TextInput
                  style={{flex:1 ,alignItems:'flex-end' ,justifyContent:'flex-end',paddingLeft:10 ,width:40}}
                  placeholder="消费满多少可以使用"
                  underlineColorAndroid={'transparent'}
                  textAlign='right'
                  keyboardType='numeric'
                  value={this.state.consumeMoney}
                  writingDirection='rtl'
                  onChangeText={(text)=>this.setState({
                    consumeMoney:text,
                  })}
                  returnKeyType='next'
                  multiline={false}
                />
            </View>
            {/* <View style={commonStyles.line_gray}/> */}
            <View style={[commonStyles.line_gray , {marginTop:10}]}/>
            {/* <TouchableHighlight
              underlayColor='rgba(255,255,255,0)'
              onPress={() => this.showActionSheet()}>
            <View style={commonStyles.itembar}>
              <Text style={commonStyles.itembar_txt}>类型</Text>
              <View style={{flex:1, flexDirection:'row',alignItems:'center', justifyContent:'center'}}>
                <Text>{this.state.eventstr}</Text>
              </View>
              <Image source={require('../../image/img_right_grey.png')} style={{width:20,height:20}} />
            </View>
            </TouchableHighlight>
      
          <View style={commonStyles.line_gray}/> */}
      
            <View style={commonStyles.line_gray} />
            <View style={{backgroundColor:'white', flexDirection:'row' , justifyContent:'center',alignItems:'center'}}>
              <Text style={{margin:20}}>有效期</Text>
              <View style={{flex:1 , flexDirection:'column' ,justifyContent:'center',backgroundColor:'blue'}}>
                <View style={commonStyles.itembar}>
                  <Text>开始时间</Text>
                  <DatePicker
                                  style={{ backgroundColor: "white" }}
                                  date={this.state.yxq_start}
                                  minDate={new Date()}
                                  mode="datetime"
                                  showIcon={false}
                                  placeholder="选择日期"
                                  format="YYYY-MM-DD HH:mm:ss"
                                  confirmBtnText="确定"
                                  cancelBtnText="取消"
                                  customStyles={{
                                      dateInput: {
                                          borderWidth: 0,
                                      }
                                  }}
                                  onDateChange={(date) => { this.setState({ yxq_start: date }) }}
                              />
                </View>
                <View style={commonStyles.line_gray}></View>
                <View style={commonStyles.itembar}>
                  <Text>结束时间</Text>
                  <DatePicker
                                  style={{ backgroundColor: "white" }}
                                  date={this.state.yxq_end}
                                  minDate={new Date()}
                                  mode="datetime"
                                  showIcon={false}
                                  placeholder="选择日期"
                                  format="YYYY-MM-DD HH:mm:ss"
                                  confirmBtnText="确定"
                                  cancelBtnText="取消"
                                  customStyles={{
                                      dateInput: {
                                          borderWidth: 0,
                                      }
                                  }}
                                  onDateChange={(date) => { this.setState({ yxq_end: date }) }}
                              />
                </View>
              </View>
            </View>
            <View style={commonStyles.line_gray} />
            <View style={{backgroundColor:'white', flexDirection:'row' , justifyContent:'center',alignItems:'center'}}>
              <Text style={{margin:20}}>投放期</Text>
              <View style={{flex:1 , flexDirection:'column' ,justifyContent:'center',backgroundColor:'blue'}}>
                <View style={commonStyles.itembar}>
                  <Text>开始时间</Text>
                  <DatePicker
                                  style={{ backgroundColor: "white" }}
                                  date={this.state.tfq_start}
                                  minDate={new Date()}
                                  mode="datetime"
                                  showIcon={false}
                                  placeholder="选择日期"
                                  format="YYYY-MM-DD HH:mm:ss"
                                  confirmBtnText="确定"
                                  cancelBtnText="取消"
                                  customStyles={{
                                      dateInput: {
                                          borderWidth: 0,
                                      }
                                  }}
                                  onDateChange={(date) => { this.setState({ tfq_start: date }) }}
                              />
                </View>
                <View style={commonStyles.line_gray}></View>
                <View style={commonStyles.itembar}>
                  <Text>结束时间</Text>
                  <DatePicker
                                  style={{ backgroundColor: "white" }}
                                  date={this.state.tfq_end}
                                  minDate={new Date()}
                                  mode="datetime"
                                  showIcon={false}
                                  placeholder="选择日期"
                                  format="YYYY-MM-DD HH:mm:ss"
                                  confirmBtnText="确定"
                                  cancelBtnText="取消"
                                  customStyles={{
                                      dateInput: {
                                          borderWidth: 0,
                                      }
                                  }}
                                  onDateChange={(date) => { this.setState({ tfq_end: date }) }}
                              />
                </View>
              </View>
            </View>
            {/* <View style={commonStyles.line_gray} />
            <TouchableHighlight
              onPress={()=>this.setlocation()}
              underlayColor='rgba(255,255,255,0)'>
            <View style={commonStyles.itembar}>
              <Text>券坐标</Text>
              <Text>{this.state.ischoose}</Text>
              <Image style={{width:20,height:20}} source={require('../../image/img_right_grey.png')}/>
            </View>
            </TouchableHighlight>
            <View style={commonStyles.line_gray}/> */}
            { saveBtn }
            </ScrollView></LmmKeyboardAvoidingView>
        );
    }

}

const mapStateToProps = state => ({
    token: state.mainmodel.token,
});

const mapDispatchToProps = dispatch => ({
    getTickets:(token,page) => {
      dispatch(getTickets(token,page))
    }
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(TicketAddItem);